<template>
  <!-- 页面容器 -->
  <div class="add-order-container">
    <!-- 页面标题 -->
    <!-- el-page-header: Element Plus页面头部组件，提供返回功能 -->
    <el-page-header
      title="返回订单列表"
      content="添加订单"
      @back="handleBack"
      class="page-header"
    />

    <!-- 添加订单表单卡片 -->
    <!-- el-card: Element Plus卡片组件，用于组织表单内容 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
        </div>
      </template>

      <!-- 订单表单 -->
      <!-- el-form: Element Plus表单组件，包含表单验证功能 -->
      <el-form
        ref="formRef"
        :model="orderForm"
        :rules="formRules"
        label-width="100px"
        v-loading="loading"
      >
        <!-- 第一行：客户和订单日期 -->
        <!-- el-row: Element Plus栅格行组件 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- el-form-item: Element Plus表单项组件 -->
            <el-form-item label="客户" prop="customer_id">
              <!-- 使用flex布局组织客户选择和按钮 -->
              <div style="display: flex; gap: 10px;">
                <!-- el-select: Element Plus下拉选择组件 -->
                <el-select
                  v-model="orderForm.customer_id"
                  placeholder="请选择客户"
                  style="flex: 1;"
                  filterable
                >
                  <!-- 遍历客户选项生成下拉列表 -->
                  <el-option
                    v-for="customer in customerOptions"
                    :key="customer.customer_id"
                    :label="customer.customer_name"
                    :value="customer.customer_id"
                  />
                </el-select>
                <!-- 选择客户按钮 -->
                <el-button type="primary" @click="openCustomerSelectDialog">
                  选择客户
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="订单日期" prop="order_date">
              <!-- el-date-picker: Element Plus日期选择器组件 -->
              <el-date-picker
                v-model="orderForm.order_date"
                type="date"
                placeholder="请选择订单日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：订单状态和订单金额 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <!-- 订单状态下拉选择 -->
              <el-select v-model="orderForm.status" placeholder="请选择订单状态" style="width: 100%">
                <!-- 遍历订单状态选项生成下拉列表 -->
                <el-option
                  v-for="status in orderStatusConfig.statusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="订单金额">
              <!-- 只读输入框显示订单总金额 -->
              <el-input
                v-model="orderTotalAmount"
                readonly
                placeholder="自动计算"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：产品和婴儿名称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品" prop="product_id">
              <!-- 使用flex布局组织产品选择和按钮 -->
              <div style="display: flex; gap: 10px;">
                <!-- 产品下拉选择组件 -->
                <el-select
                  v-model="orderForm.product_id"
                  placeholder="请选择产品"
                  style="flex: 1;"
                  filterable
                  @change="onProductChange"
                >
                  <!-- 遍历产品选项生成下拉列表 -->
                  <el-option
                    v-for="product in productOptions"
                    :key="product.product_id"
                    :label="product.product_name"
                    :value="product.product_id"
                  >
                    <!-- 显示产品名称和价格信息 -->
                    <span style="float: left">{{ product.product_name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">¥{{ product.retail_price || product.price || product.wholesale_price }}</span>
                  </el-option>
                </el-select>
                <!-- 选择产品按钮 -->
                <el-button type="primary" @click="openProductSelectDialog">
                  选择产品
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="婴儿名称" prop="baby_name">
              <!-- 婴儿名称输入框 -->
              <el-input
                v-model="orderForm.baby_name"
                placeholder="请输入婴儿名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：数量、单价和小计 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <!-- el-input-number: Element Plus数字输入框组件 -->
              <el-input-number
                v-model="orderForm.quantity"
                :min="1"
                controls-position="right"
                @change="calculateSubtotal"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="单价" prop="unit_price">
              <!-- 单价数字输入框，支持小数点后两位 -->
              <el-input-number
                v-model="orderForm.unit_price"
                :min="0"
                :precision="2"
                controls-position="right"
                @change="calculateSubtotal"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="小计" prop="subtotal">
              <!-- 只读输入框显示小计金额 -->
              <el-input
                v-model="orderForm.subtotal"
                readonly
                placeholder="自动计算"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 订单备注 -->
        <el-form-item label="订单备注" prop="notes">
          <!-- type="textarea": 文本域模式的输入框 -->
          <el-input
            v-model="orderForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入订单备注"
          />
        </el-form-item>

        <!-- 附加服务选项 -->
        <!-- el-divider: Element Plus分割线组件 -->
        <el-divider content-position="left">附加服务</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="照片" prop="photo">
              <!-- el-switch: Element Plus开关组件 -->
              <el-switch
                v-model="orderForm.photo"
                :active-value="1"
                :inactive-value="0"
                active-text="有"
                inactive-text="无">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="手脚印" prop="hand_foot_print">
              <el-switch
                v-model="orderForm.hand_foot_print"
                :active-value="1"
                :inactive-value="0"
                active-text="有"
                inactive-text="无">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="胎毛" prop="baby_hair">
              <el-switch
                v-model="orderForm.baby_hair"
                :active-value="1"
                :inactive-value="0"
                active-text="有"
                inactive-text="无">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="脐带" prop="umbilical_cord">
              <el-switch
                v-model="orderForm.umbilical_cord"
                :active-value="1"
                :inactive-value="0"
                active-text="有"
                inactive-text="无">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表单操作按钮 -->
        <el-form-item class="form-actions">
          <!-- 取消按钮 -->
          <el-button @click="handleCancel">取消</el-button>
          <!-- 保存订单按钮 -->
          <!-- :loading="saveLoading": 按钮加载状态 -->
          <el-button type="primary" @click="handleSubmit" :loading="saveLoading">
            保存订单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 客户选择对话框 -->
    <!-- CustomerSelectDialog: 自定义客户选择对话框组件 -->
    <CustomerSelectDialog
      v-model="customerSelectDialogVisible"
      @select="handleCustomerSelect"
    />

    <!-- 产品选择对话框 -->
    <!-- ProductSelectDialog: 自定义产品选择对话框组件 -->
    <ProductSelectDialog
      v-model="productSelectDialogVisible"
      @select="handleProductSelect"
    />
  </div>
</template>

<script setup>
/**
 * 添加订单页面组件选项配置
 */
defineOptions({
  name: 'AddOrderView'
})

// 从Vue中导入所需的API
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

// 导入Element Plus组件和相关API
import { ElMessage } from 'element-plus'

// 导入订单相关的API函数
import { createOrder } from '@/api/SalesOrders'
import { getCustomerList } from '@/api/Customers'
import { getProductList } from '@/api/Products'
// 导入订单状态配置
import orderStatusConfig from '@/utils/orderStatusConfig'
// 导入客户选择组件
import CustomerSelectDialog from '@/components/CustomerSelectDialog.vue'
// 导入产品选择组件
import ProductSelectDialog from '@/components/ProductSelectDialog.vue'

// 获取路由实例
const router = useRouter()

// 响应式数据定义
const formRef = ref(null)           // 表单引用
const loading = ref(false)          // 加载状态
const saveLoading = ref(false)      // 保存按钮加载状态

// 客户和产品选项
const customerOptions = ref([])
const productOptions = ref([])

// 客户和产品选择对话框显示状态
const customerSelectDialogVisible = ref(false)
const productSelectDialogVisible = ref(false)

// 订单表单数据
const orderForm = ref({
  customer_id: '',
  order_date: new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10),  // 默认设置为今天（修正时区问题）
  status: 1,  // 默认状态改为数字代码1（待处理）
  notes: '',
  product_id: '',
  quantity: 1,
  unit_price: 0.00,
  subtotal: 0.00,
  baby_name: '',
  photo: 0,
  hand_foot_print: 0,
  baby_hair: 0,
  umbilical_cord: 0
})

// 计算订单总金额
const orderTotalAmount = computed(() => {
  return orderForm.value.subtotal || '0.00'
})

// 表单验证规则
const formRules = {
  customer_id: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  order_date: [
    { required: true, message: '请选择订单日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ],
  product_id: [
    { required: true, message: '请选择产品', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'change' }
  ],
  unit_price: [
    { required: true, message: '请输入单价', trigger: 'change' }
  ],
  subtotal: [
    { required: true, message: '请输入小计', trigger: 'change' }
  ]
}

/**
 * 重置表单
 */
const resetForm = () => {
  // 保存需要保留的字段
  const preservedData = {
    customer_id: orderForm.value.customer_id,
    baby_name: orderForm.value.baby_name
  }

  // 重置表单数据为初始值，但保留客户信息和婴儿名称
  orderForm.value = {
    customer_id: preservedData.customer_id,
    order_date: new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10),  // 默认设置为今天（修正时区问题）
    status: 1,
    notes: '',
    product_id: '',
    quantity: 1,
    unit_price: 0.00,
    subtotal: 0.00,
    baby_name: preservedData.baby_name,
    photo: 0,
    hand_foot_print: 0,
    baby_hair: 0,
    umbilical_cord: 0
  }

  // 重置表单验证状态
  formRef.value?.resetFields()
}

/**
 * 禁用未来日期
 * @param {Date} date - 日期对象
 * @returns {boolean} 是否禁用
 */
const disabledDate = (date) => {
  return date.getTime() > Date.now()
}

/**
 * 获取客户和产品选项数据
 */
const getOptionsData = async () => {
  try {
    loading.value = true;

    // 获取客户列表
    const customerRes = await getCustomerList({ pageSize: 1000 })
    customerOptions.value = customerRes.data || []

    // 获取产品列表
    const productRes = await getProductList({ pageSize: 1000 })
    productOptions.value = productRes.data || []
  } catch (error) {
    console.error('获取选项数据失败:', error)
    ElMessage.error('获取选项数据失败，请稍后重试！')
  } finally {
    loading.value = false;
  }
}

/**
 * 打开客户选择对话框
 */
const openCustomerSelectDialog = () => {
  customerSelectDialogVisible.value = true
}

/**
 * 处理客户选择结果
 */
const handleCustomerSelect = (selectedCustomer) => {
  if (selectedCustomer) {
    orderForm.value.customer_id = selectedCustomer.customer_id
  }
}

/**
 * 打开产品选择对话框
 */
const openProductSelectDialog = () => {
  productSelectDialogVisible.value = true
}

/**
 * 处理产品选择结果
 */
const handleProductSelect = (selectedProduct) => {
  if (selectedProduct) {
    orderForm.value.product_id = selectedProduct.product_id
    // 触发产品变化事件，自动设置单价
    onProductChange(selectedProduct.product_id)
  }
}

/**
 * 提交订单表单
 */
const handleSubmit = async () => {
  // 表单验证
  try {
    await formRef.value.validate()
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请填写完整的订单信息')
    return
  }

  try {
    saveLoading.value = true

    // 确保订单状态是数字代码而不是字符串
    let orderStatus = orderForm.value.status;
    if (typeof orderStatus === 'string') {
      orderStatus = orderStatusConfig.getStatusValueByLabel(orderStatus);
    }

    // 准备提交数据
    const submitData = {
      customer_id: orderForm.value.customer_id,
      order_date: orderForm.value.order_date,
      status: orderStatus,
      notes: orderForm.value.notes,
      product_id: orderForm.value.product_id,
      quantity: orderForm.value.quantity,
      unit_price: orderForm.value.unit_price,
      subtotal: orderForm.value.subtotal,
      baby_name: orderForm.value.baby_name,
      photo: orderForm.value.photo,
      hand_foot_print: orderForm.value.hand_foot_print,
      baby_hair: orderForm.value.baby_hair,
      umbilical_cord: orderForm.value.umbilical_cord
    }
    // 添加总金额字段
    submitData.total_amount = orderForm.value.subtotal;

    // 创建订单
    await createOrder(submitData)
    ElMessage.success('新增订单成功！')

    // 重置表单，但不跳转页面
    resetForm()
  } catch (error) {
    console.error('保存订单失败:', error)
    ElMessage.error(`保存订单失败：${error.msg || error.message || '请稍后重试！'}`)
  } finally {
    saveLoading.value = false
  }
}

/**
 * 计算订单小计
 */
const calculateSubtotal = () => {
  const quantity = parseFloat(orderForm.value.quantity) || 0
  const unitPrice = parseFloat(orderForm.value.unit_price) || 0
  orderForm.value.subtotal = (quantity * unitPrice).toFixed(2)
}

/**
 * 当产品选择变化时
 * @param {string} productId - 产品ID
 */
const onProductChange = (productId) => {
  if (!productId) {
    // 如果没有选择产品，重置单价和小计
    orderForm.value.unit_price = 0.00
    orderForm.value.subtotal = 0.00
    return
  }

  // 查找选中的产品
  const selectedProduct = productOptions.value.find(product => product.product_id === productId)
  if (selectedProduct) {
    // 设置单价为产品零售价，确保是数字类型
    orderForm.value.unit_price = parseFloat(selectedProduct.retail_price) ||
                    parseFloat(selectedProduct.price) ||
                    parseFloat(selectedProduct.wholesale_price) || 0.00

    // 确保数量至少为1
    if (!orderForm.value.quantity || orderForm.value.quantity < 1) {
      orderForm.value.quantity = 1
    }
    // 重新计算小计
    calculateSubtotal()
  }
}

/**
 * 返回订单列表
 */
const handleBack = () => {
  router.push('/orders')
}

/**
 * 取消添加订单
 */
const handleCancel = () => {
  router.push('/orders')
}

// 组件挂载时获取选项数据
onMounted(() => {
  getOptionsData()
})
</script>

<style scoped>
/**
 * 添加订单页面样式部分
 * 使用scoped属性确保样式只作用于当前组件
 */

/* 页面容器样式 */
.add-order-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
}

/* 表单卡片样式 */
.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

/* 表单操作按钮样式 */
.form-actions {
  text-align: right;
  margin-top: 20px;
}

/* 附加服务区域样式 */
.el-divider {
  margin: 30px 0 20px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .add-order-container {
    padding: 10px;
  }

  .el-row {
    flex-direction: column;
    gap: 15px;
  }

  .el-col {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
